package com.ilab.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ilab.model.Employee;
import com.ilab.service.EmployeeService;
import com.ilab.web.forms.EmployeeForm;

public class LoginAction extends DispatchAction {
	
	private EmployeeService employeeService;
	
	public void setEmployeeService(EmployeeService employeeService) {
		System.out.println("**********************通过setEmployeeService*********************************");
		this.employeeService = employeeService;
	}

	// 响应登陆请求
	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		// 通过下面语句，可以直接获取到spring容器实例。即我们前面讲的ApplicationContext
//		WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext());
		
		// 从spring容器中获取bean
//		EmployeeService employeeService = (EmployeeService) ctx.getBean("employeeService"); 
		
		
		// 取出表单， 我们先打通， 简单验证
		EmployeeForm employeeForm = (EmployeeForm) form;
		
		// 构建一个Employee对象
		Employee employee = new Employee();
		employee.setId(Integer.parseInt(employeeForm.getId()));
		employee.setPwd(employeeForm.getPwd());
		employee = employeeService.checkEmployee(employee);

		if(employee != null) {
			// 把雇员信息放入session，后面可以使用
			request.getSession().setAttribute("loginuser", employee);
			
			return mapping.findForward("ok");
		} else {
			return mapping.findForward("err");
		}
	}
	
	// 响应注销请求
	public ActionForward logout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		request.getSession().invalidate();
		return mapping.findForward("out");
	}
	
	// 到主界面
	public ActionForward goToMain(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 没有对身份验证[过滤器]
		
		if(request.getSession().getAttribute("loginuser") != null) {
			return mapping.findForward("ok");
		} else {
			return mapping.findForward("err");
		}
		
	}
}
